import route from 'koa-route';
import { v4 } from 'uuid'
import { Room } from '../interface';
import { Globel } from '../lib/tools';
//创建房间者属性
interface CreaterInfo {
    userid: string;
    username: string;
    roomname: string;
}
//创建房间
export const createRoom = route.post('/createroom', async (ctx) => {
    let creater: CreaterInfo = ctx.request.body;
    let room_id = v4();
    Globel.rooms.set(room_id,new Room(
        creater.username,
        creater.userid,
        room_id,
        creater.roomname,
        1,
        new Date().getTime()
    ))
    ctx.body = {
        status: 1,
        data:room_id,
        message: '创建房间成功'
    }
})
export const joinRoom = route.get('/joinRoom',async(ctx)=>{
    let roomid = ctx.request.query.id as string;
    let room = Globel.rooms.get(roomid);
    if(!room){
        ctx.body = {
            status:0,
            data:'房间不存在'
        }
    }else{
        if(room.game.playerMap.size>=3){
            ctx.body = {
                status:0,
                data:'房间已满'
            }
        }else{
            room.usercount++;
            ctx.body = {
                status:1,
                data:roomid
            }
        }
    }
})
//获取房间列表
export const getRoomList = route.get('/getroomlist', async (ctx) => {
    let arr:any[] = [];
    Globel.rooms.forEach(v=>{
        arr.push({
            roomid:v.roomid,
            roomname:v.roomname,
            adminname:v.adminname,
            adminid:v.adminid,
            usercount:v.usercount,
            create_time:v.create_time
        })
    });
    arr.sort(function(a,b){
        return b.create_time-a.create_time;
    })
    ctx.body = {
        status: 1,
        data: arr
    }
})